<!-- 角色列表区域 -->
import { async } from 'q';
<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- 添加角色按钮 -->
            <el-button type="primary" @click="addRole">添加角色</el-button>

            <!-- 添加角色对话框 -->
            <el-dialog title="添加角色" :visible.sync="addRoleVisiable" width="30%" :before-close="handleClose">

                <el-form :model="addRoleMsg" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRoleMsg.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input v-model="addRoleMsg.roleDesc"></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="addRoleVisiable = false">取 消</el-button>
                    <el-button type="primary" @click="submitAddRole">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 编辑角色对话框 -->
            <el-dialog title="编辑角色" :visible.sync="modifyRoleVisable" width="30%" :before-close="handleClose">

                <el-form :model="modifyRoleMsg" :rules="rules" ref="modifyRoleForm" label-width="100px"
                    class="demo-ruleForm">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="modifyRoleMsg.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input v-model="modifyRoleMsg.roleDesc"></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="modifyRoleVisable = false">取 消</el-button>
                    <el-button type="primary" @click="submitModifyRole">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 确认删除对话框 -->
            <el-dialog :visible.sync="deleteRoleVisiable" width="30%" :before-close="handleClose">
                <span>真的要删除这条信息吗？</span>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="deleteRoleVisiable = false">取 消</el-button>
                    <el-button type="primary" @click="deleteRole">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 分配权限对话框 -->
            <el-dialog title="管理权限" :visible.sync="showSetRightDialog" width="30%" :before-close="handleClose" @close="cleanCheckKey">
                <!-- 树形属性展示区 -->
                <el-tree :data="treeData" :props="treeProps"  show-checkbox node-key="id" default-expand-all	 :default-checked-keys="checkKey" ref="treeRef"></el-tree>
                <!-- show-checkbox显示复选框 default-expand-all默认打开一级标签 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showSetRightDialog = false">取 消</el-button>
                    <el-button type="primary" @click="setRoleRight">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 显示角色区域 -->
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- {{scope.row}} -->
                        <el-row :class="['bdbottom',index===0? 'bdtop':'','vcenter']"
                            v-for="(item,index) in scope.row.children" :key="item.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5" class="center">
                                <el-tag plain type="primary" closable @close="deleteRoleRight(scope.row,item.id)">
                                    {{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i1===0? '':'bdtop','vcenter']" v-for="(item1,i1) in item.children"
                                    :key="item1.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="deleteRoleRight(scope.row,item1.id)">
                                            {{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item2) in item1.children" :key="item2.id"
                                            closable @close="deleteRoleRight(scope.row,item2.id)">{{item2.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" width="60" label="#">
                </el-table-column>
                <el-table-column prop="roleName" label="角色名称" width="180">
                </el-table-column>
                <el-table-column prop="roleDesc" label="角色描述" width="180px">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="modifyRole(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="showDeleteRole(scope.row)">删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-s-tools" @click="SetDialogVisiable(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-card>


    </div>
</template>

<script>
    export default {
        created() {
            this.getRoleList()
        },
        data() {
            return {
                roleList: [],
                //是否显示添加角色视图
                addRoleVisiable: false,
                //是否显示编辑角色视图
                modifyRoleVisable: false,
                //是否删除角色
                deleteRoleVisiable: false,
                //校验规则
                rules: {
                    roleName: [{
                            required: true,
                            message: '用户名不能为空',
                            trigger: 'blur'
                        },
                        {
                            min: 2,
                            max: 10,
                            message: '角色名长度在2到10之间',
                            trigger: 'blur'
                        }
                    ]
                },
                addRoleMsg: {
                    roleName: '',
                    roleDesc: ''
                },
                modifyRoleMsg: {
                    roleName: '',
                    roleDesc: ''
                },
                modifyID: null,
                deleteID: null,
                //是否显示管理权限对话框
                showSetRightDialog:false,
                treeData:[],
                treeProps:{
                    label:'authName',
                    children:'children'
                },
                //默认选中的权限
                checkKey:[],
                // 修改权限的id
                setRightsID:''
            }
        },
        methods: {
            //获取角色信息
            async getRoleList() {
                const {
                    data: res
                } = await this.$http.get('roles')
                // console.log(res)
                if (res.meta.status !== 200) {
                    return this.$message.error('获取用户列表失败')
                }
                this.roleList = res.data
            },
            //关闭视图
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            // 添加角色
            addRole() {
                this.addRoleVisiable = true
            },
            async submitAddRole() {
                this.addRoleVisiable = false
                console.log(this.addRoleMsg);
                const {
                    data: res
                } = await this.$http.post('roles', this.addRoleMsg)
                if (res.meta.status !== 201) {
                    return this.$message.error('添加用户失败！')
                }
                this.getRoleList()
            },
            //编辑角色
            //获取页面传递的scope.row参数
            modifyRole(selectRole) {
                this.modifyRoleVisable = true
                this.modifyRoleMsg.roleName = selectRole.roleName
                this.modifyRoleMsg.roleDesc = selectRole.roleDesc
                this.modifyID = selectRole.id
                console.log(selectRole)
            },
            submitModifyRole() {
                this.$refs['modifyRoleForm'].validate(async (valid) => {
                    if (valid) {
                        const {
                            data: res
                        } = await this.$http.put(`roles/${this.modifyID}`, this.modifyRoleMsg)
                        if (res.meta.status !== 200) {
                            return this.$message.error(`${res.meta.status}修改用户状态失败`)
                        }
                        this.$message.success('修改用户状态成功')
                        this.getRoleList()
                        this.modifyRoleVisable = false
                    }
                });
            },
            //删除角色
            showDeleteRole(role) {
                this.deleteRoleVisiable = true
                this.deleteID = role.id
            },
            async deleteRole() {
                const {
                    data: res
                } = await this.$http.delete(`roles/${this.deleteID}`)
                if (res.meta.status !== 200) {
                    return this.$message.error(`删除失败`)
                }
                this.$message.success('删除成功')
                this.getRoleList()
                this.deleteRoleVisiable = false
            },
            //删除用户权限
            deleteRoleRight(role, rightid) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    // this.$message({
                    //     type: 'success',
                    //     message: '删除成功!'
                    // })
                    const {
                        data: res
                    } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除失败')
                    }
                    //将返回值直接重新赋值给role.children，就不会重新刷新界面获取整个表单
                    role.children = res.data
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            //管理用户权限
            async SetDialogVisiable(role){
                const {data:res} = await this.$http.get('rights/tree')
                this.treeData = res.data
                this.showSetRightDialog = true
                this.getCheckRights(role)
                this.setRightsID = role.id
            },
            //获取所有被选中的三级权限
            getCheckRights(role){
                // console.log(role.children.children.children)
                // console.log(role.children);
                role.children.forEach(item => {
                    item.children.forEach(item1=>{
                        item1.children.forEach(item2=>{
                            this.checkKey.push(item2.id)
                        })
                    })
                });
            },
            cleanCheckKey(){
                this.checkKey = []
            },
            //修改用户权限
            // getCheckedTrees()
            // getHalfCheckedTrees()
            async setRoleRight(){
                const setRights = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]
                const idStr = setRights.join(',')
                console.log(idStr)
                console.log(this.setRightsID);
                const {data:res} = await this.$http.post(`roles/${this.setRightsID}/rights`,{rids:idStr})
                console.log(res)
                if(res.meta.status!==200){
                    return this.$message.error('修改用户权限失败')
                }
                this.getRoleList()

                this.showSetRightDialog = false
            }
        }
    }
</script>
<style scoped>
    /* @import url(); 引入css类 */
    .el-col {
        text-align: center;
    }

    .el-tag {
        margin: 7px
    }

    .bdtop {
        border-top: 1px solid #eeeeee
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center
    }
</style>